package com.example.last.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import com.example.last.entity.Questions;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

// 注解作用是注册处理器，还有一种注册方式是通过xml文件配置
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({List.class}) // 修改为List.class
public class JsonStringArrayTypeHandler extends BaseTypeHandler<List<Questions>> {
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Questions> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, toJson(parameter));
    }

    @Override
    public List<Questions> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return toObject(rs.getString(columnName));
    }

    @Override
    public List<Questions> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toObject(rs.getString(columnIndex));
    }

    @Override
    public List<Questions> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toObject(cs.getString(columnIndex));
    }

    private String toJson(List<Questions> params) {
        try {
            return mapper.writeValueAsString(params);
        } catch (Exception e) {
            throw new RuntimeException("Error when converting List<Question> to JSON string", e);
        }
    }

    private List<Questions> toObject(String content) {
        if (content != null && !content.isEmpty()) {
            try {
                // 修改为List<Question>的类型
                return mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, Questions.class));
            } catch (Exception e) {
                throw new RuntimeException("Error when converting JSON string to List<Question>", e);
            }
        } else {
            return null;
        }
    }
}
